package com.hibernate.manage.tpl;
import java.io.Serializable;
import java.util.concurrent.ExecutionException;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.google.common.cache.LoadingCache;
import com.hibernate.base.HibernateUtils;
import com.hibernate.modle.tp.AbstractInfDate;

public class InfDateManage<K, T extends AbstractInfDate<K>> extends CatchDateManage<K,T> implements InfDateManageIfe<K, T>{
	private Class<T> theClass;
	public InfDateManage(Class<T> theClass) {
		super(theClass);
		this.theClass = theClass;
	}
	
	public void writeModle(K i, T t) {	
		getDateCatch().put(i, t);
	}

	public T readModle(K i) {
		try {
			return getDateCatch().get(i);
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	@SuppressWarnings("deprecation")
	public T readInit(K i) throws InstantiationException, IllegalAccessException{
		Session session = HibernateUtils.getSession();
		Transaction tx = session.beginTransaction();
		try {

			T u = (T) session.get(theClass, (Serializable) i);
			tx.commit();
			if(u != null) {
				u.loadOver();	
			}else {
				u = (T)theClass.newInstance();
				u.initData(i);
			}
			return u;
		} catch (HibernateException e) {
			if (tx != null)
				tx.rollback();
			e.printStackTrace();
		}
		return null;
	}
	
	public  void writeCatchToSql(T t) {
		Session session = HibernateUtils.getSession();
		Transaction tx = session.beginTransaction();
		try {
			session.saveOrUpdate(t);
			tx.commit();
		} catch (HibernateException e) {
			if (tx != null)
				tx.rollback();
			e.printStackTrace();
		}
	}
	
	public  LoadingCache<K,T> getCatch() {
		return getDateCatch();
	}
}
